/***************************************************
 * 2、线性表A，长度为n，采用链式存储结构，表头指针为H，
 * 请设计一个算法，删除链表H中元素值为b的所有结点。
***************************************************/

#include<stdio.h>
#include<malloc.h>

struct NODE;
typedef struct NODE node;
struct NODE{int data;node* next;};

// 返回删除元素的个数
int delete_by_value(node* h,int b){
    int n = 0; // 被删元素的个数
    node* p = NULL;
    while(h->next){
        if(h->next->data==b){
            ++n;
            p = h->next;
            h->next = p->next;
            free(p);
        }
        h = h->next;
    }
    return n;
}

void print_linkedlist(const node* p){
    p = p->next;
    while(p){printf("%d ",p->data);p=p->next;}printf("\n");
}

int main(){
    node head;
    node* h = &head;
    node* p = h;
    int n = 10, i = 0;
    int A[10] = {1,2,3,2,1,4,5,6,5,4};

    for(i=0;i<n;i++){
        p->next = malloc(sizeof(node)); 
        p=p->next;
        p->data = A[i];
    }
    p->next=NULL;

    print_linkedlist(h);

    int test[4] = {1,3,12,6};
    int t;
    for(i=0;i<4;i++){
        t = delete_by_value(h,test[i]);
        printf("Deleting %2d, %2d element(s) removed. Now: ",test[i],t);
        print_linkedlist(h);
    }

    // clean-up
    while(h){p = h;h=h->next;free(p);}
    return 0;
}